package TableAdditions;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import Tables.CustomerUnitPriceTableInterface;
import Utility.Customer;
import Utility.Product;


public class CustomerUnitPriceTableAddition extends JFrame {
    
	public String specialprice;
	public float specialPrice;
	public boolean customerFlag=false;
	public boolean productFlag=false;
	public Customer[] customers;
	public Product[] productArray;
	public static int selectedProductIndex;
	public static int selectedCustomerIndex;
	public float newSpecialPrice;
	public boolean specialPriceChangeFlag=false;
	
	Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    String url = "jdbc:mysql://localhost:3306/mydb";
    String user = "root";
    String password = "qweasdzxc";
	
	
	CustomerUnitPriceTableInterface cti;
	private JTextField specialPriceTextField;
	public CustomerUnitPriceTableAddition(final CustomerUnitPriceTableInterface cti) {
		
		super("Müşteri Birim Fiyat Ekleme Ekranı");
		this.cti = cti;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(600,200);
		getContentPane().setLayout(null);
		
		JLabel lblMteri = new JLabel("Müşteri");
		lblMteri.setBounds(12, 12, 70, 15);
		getContentPane().add(lblMteri);
		
		JComboBox customerComboBox = new JComboBox();
		customerComboBox.setBounds(84, 12, 170, 24);
		getContentPane().add(customerComboBox);
		
		JLabel lblrn = new JLabel("Ürün");
		lblrn.setBounds(298, 12, 70, 15);
		getContentPane().add(lblrn);
		
		
		JComboBox productComboBox = new JComboBox();
		productComboBox.setBounds(357, 12, 170, 24);
		getContentPane().add(productComboBox);
		
		specialPriceTextField = new JTextField();
		specialPriceTextField.setBounds(164, 59, 138, 24);
		getContentPane().add(specialPriceTextField);
		specialPriceTextField.setColumns(10);
		
		JButton addButton = new JButton("Ekle");
		addButton.setBounds(322, 59, 100, 25);
		getContentPane().add(addButton);
		
		addButton.addMouseListener(new MouseListener() {
			
			
			@Override
			public void mouseClicked(MouseEvent e) {
				
				if(specialPriceChangeFlag){
						if(specialPrice!=newSpecialPrice){
							System.out.println("special price changed");
							
							if(DatabaseFunctions.previousSpecialPrice){
								try {
									con = (Connection) DriverManager.getConnection(url, user, password);
							        st = (Statement) con.createStatement();
									st.executeUpdate("UPDATE special_price set special_price='"+newSpecialPrice+"' " +
											"WHERE special_price_product_id='"+productArray[selectedProductIndex-1].getProductId()+"'  " +
													"and special_price_customer_id='"+customers[selectedCustomerIndex-1].getCustomerId()+"' ");
									int messageType = JOptionPane.PLAIN_MESSAGE;   
						            JOptionPane.showMessageDialog(null, "Kayıt Alınmıştır", "Uyarı!!", messageType);
									
									
								} catch (SQLException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
							}
							else{
								try {
									con = (Connection) DriverManager.getConnection(url, user, password);
							        st = (Statement) con.createStatement();
									st.executeUpdate("INSERT INTO special_price (special_price_customer_id,special_price_product_id,special_price) " +
											"VALUES ('"+customers[selectedCustomerIndex-1].getCustomerId()+"','"+productArray[selectedProductIndex-1].getProductId()+"'" +
													",'"+newSpecialPrice+"')");
									int messageType = JOptionPane.PLAIN_MESSAGE;   
						           JOptionPane.showMessageDialog(null, "Kayıt Alınmıştır", "Uyarı!!", messageType);
								
								} catch (SQLException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
							}
						}
						else{
							System.out.println("special price is same");
						}
				}else{
					System.out.println("special price is same");
				}
				
				  	cti.addNewItem();
			        setVisible(false);
			        dispose();
				
				
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
	 	
        try {
            con = (Connection) DriverManager.getConnection(url, user, password);
            st = (Statement) con.createStatement();
            rs=st.executeQuery("SELECT * from customer where activity = '1' order by customer_name");
            int i=0,counter=0;
            while(rs.next())
            	++counter;
            
            customerComboBox.addItem("Müşteri Adı");
            if(counter>0){
            rs.first();
            customers=new Customer[counter];
            customers[i]=new Customer();
            customers[i].setCustomerName(rs.getString("customer_name"));
        	customers[i].setCustomerId(rs.getInt("customer_id"));
            i++;
            while(rs.next())
            {
            	customers[i]=new Customer();
            	customers[i].setCustomerName(rs.getString("customer_name"));
            	customers[i].setCustomerId(rs.getInt("customer_id"));
            	++i;
            }
            
            }
            
            for(int m=0;m<customers.length;m++){
            	customerComboBox.addItem(customers[m].getCustomerName());
            }
            
            con.close();
            
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(main.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(main.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
        
        
        try {
            con = (Connection) DriverManager.getConnection(url, user, password);
            st = (Statement) con.createStatement();
            rs=st.executeQuery("SELECT * from product where activity = '1' order by product_name");
            int i=0,counter=0;
            while(rs.next())
            	++counter;
            rs.first();
            productComboBox.addItem("Ürün Adı");
            if(counter>0){
            productArray=new Product[counter];
            productArray[i]=new Product();
            productArray[i].setProductName(rs.getString("product_name"));
            productArray[i].setProductId(rs.getInt("product_id"));
            i++;
            while(rs.next())
            {
            	productArray[i]=new Product();
            	productArray[i].setProductName(rs.getString("product_name"));
                productArray[i].setProductId(rs.getInt("product_id"));
            		++i;
        
            }
            
            }
            
            for(int m=0;m<productArray.length;m++){
            	productComboBox.addItem(productArray[m].getProductName());
            }
            con.close();
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(main.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(main.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }        
		setVisible(true);  
		
		customerComboBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent event) {
				
				
                JComboBox comboBox = (JComboBox) event.getSource();
       	     
                //
                // Print the selected items and the action command.
                //
                Object selected = comboBox.getSelectedItem();
                selectedCustomerIndex=comboBox.getSelectedIndex();
                System.out.println("Selected Item  = " + selected);
                String command = event.getActionCommand();
                System.out.println("Action Command = " + command);
                
                if(selected.toString().equals("Müşteri Adı")){
                	customerFlag=false;
                }
                else{
                	customerFlag=true;
                }
                
                if(productFlag && customerFlag){
                	System.out.println("special price ready to get");
                	specialPrice=DatabaseFunctions.getSpecialPrice(customers[selectedCustomerIndex-1].getCustomerId(),
                			productArray[selectedProductIndex-1].getProductId());
                	specialPriceTextField.setText(Float.toString(specialPrice));  
                	
                }
				
				
				
				
				
				
				
			}
		});
		
productComboBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent event) {
				
				
                JComboBox comboBox = (JComboBox) event.getSource();
       	     
                //
                // Print the selected items and the action command.
                //
                Object selected = comboBox.getSelectedItem();
                selectedProductIndex=comboBox.getSelectedIndex();
                System.out.println("Selected Item  = " + selected);
                String command = event.getActionCommand();
                System.out.println("Action Command = " + command);
                
                if(selected.toString().equals("Ürün Adı")){
                	productFlag=false;
                }
                else{
                	productFlag=true;
                }
                
                
                if(productFlag && customerFlag){
                	System.out.println("special price ready to get");
                	
                	specialPrice=DatabaseFunctions.getSpecialPrice(customers[selectedCustomerIndex-1].getCustomerId(),
                			productArray[selectedProductIndex-1].getProductId());
                	specialPriceTextField.setText(Float.toString(specialPrice));  	
                	
                }
                
			}
		});

	specialPriceTextField.getDocument().addDocumentListener(new DocumentListener() {

		@Override
		public void changedUpdate(DocumentEvent arg0) {
			try{
				newSpecialPrice=Float.parseFloat(specialPriceTextField.getText());
				System.out.println("specialPrice= "+specialPrice);
				System.out.println("newSpecialPrice= "+newSpecialPrice);
				specialPriceChangeFlag=true;
			}catch(NumberFormatException e){
				specialPriceTextField.setText("");
				specialPriceChangeFlag=true;
				
			}
		}

		@Override
		public void insertUpdate(DocumentEvent arg0) {
			try{
				newSpecialPrice=Float.parseFloat(specialPriceTextField.getText());
				System.out.println("specialPrice= "+specialPrice);
				System.out.println("newSpecialPrice= "+newSpecialPrice);
				specialPriceChangeFlag=true;
			}catch(NumberFormatException e){
				specialPriceTextField.setText("");
				newSpecialPrice=Float.parseFloat("0");
				specialPriceChangeFlag=true;
				
			}	
		}

		@Override
		public void removeUpdate(DocumentEvent arg0) {
			try{
				newSpecialPrice=Float.parseFloat(specialPriceTextField.getText());
				System.out.println("specialPrice= "+specialPrice);
				System.out.println("newSpecialPrice= "+newSpecialPrice);
				specialPriceChangeFlag=true;
			}catch(NumberFormatException e){
				specialPriceTextField.setText("");
				newSpecialPrice=Float.parseFloat("0");
				specialPriceChangeFlag=true;
				
			}	
		}
		
	});
		
		
	}
	
	
	
	
	
}
